<template>
  <el-card class="box-card node-manage" v-loading="loading">
    <template #header>
      <div class="card-header">
        <span v-if="flowType == 0">社科基金申报流程管理</span>
        <span v-else-if="flowType == 1">基层理论宣讲先进集体申报流程管理</span>
        <span v-else-if="flowType == 2">基层理论宣讲先进个人申报流程管理</span>
        <span v-else-if="flowType == 3">优秀宣讲报告申报流程管理</span>
        <span v-else-if="flowType == 4">优秀宣讲微视频申报流程管理</span>
      </div>
    </template>

    <div class="node-tips">
      <span v-if="flowType == 0">为保障先进申报流程有效安全运转，明确各项先进申报审批流程，特制定社科基金申报审批流程。</span>
      <span v-else-if="flowType == 1">为保障先进申报流程有效安全运转，明确各项先进申报审批流程，特制定基层理论宣讲先进集体申报审批流程。</span>
      <span v-else-if="flowType == 2">为保障先进申报流程有效安全运转，明确各项先进申报审批流程，特制定基层理论宣讲先进个人申报审批流程。</span>
      <span v-else-if="flowType == 3">为保障先进申报流程有效安全运转，明确各项先进申报审批流程，特制定优秀宣讲报告申报审批流程。</span>
      <span v-else-if="flowType == 4">为保障先进申报流程有效安全运转，明确各项先进申报审批流程，特制定优秀宣讲微视频申报审批流程。</span>
    </div>

    <el-button type="primary" @click="addNodeItem">添加审批节点</el-button>
    
    <div v-for="(item, index) in nodeList" :key="index" class="node-list">
      <div>
        <el-row>
          <el-col :span="2" style="padding-top: 16px; padding-right: 16px; text-align: right;">节点 {{ index + 1 }}</el-col>
          <el-col :span="22" style="border: 1px solid #ccc;">
            <!-- 名称+按钮 -->
            <div class="node-title">
              <span>{{ item.nodeName }}</span>
              <div>
                <el-button
                  type="primary"
                  link
                  @click="nodeEdit(item)"
                  >编辑</el-button
                >
                <el-button
                  type="warning"
                  link
                  @click="nodeDelete(item)"
                  >删除</el-button
                >
              </div>
            </div>

            <!-- 详细内容 -->
            <div class="node-detail">
              <p>审批节点说明：{{ item.remark }}</p>
            </div>

            <!-- 审批人 -->
            <el-row style="padding: 16px;">
              <el-col :span="3" class="add-person">
                <el-icon @click="addApprovalPerson(item)">
                  <Plus/>
                </el-icon><br/>
                添加审批人
              </el-col>
              
              <el-col :span="21">
                <div class="person-detail" v-for="(pitem, pindex) in item.members" :key="pindex">
                  <el-icon>
                    <Avatar />
                  </el-icon>
                  <div class="person-info">
                    <span style="font-weight: bold;margin-right: 8px;font-size: 16px;">{{ pitem.approvalName }}  </span>
                  </div>
                  <el-icon class="close-icon" @click="deleteApprovalPerson(pitem, item)">
                    <CircleClose />
                  </el-icon>
                </div>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </div>
    </div>

    <add-Node v-model:visible="addNodeVisible" :addNodeTitle="addNodeTitle" @addNodeChange="addNodeChange" :nodeForm="currentNode" ref="addNodeRef" />

    <add-member v-model:visible="addUserVisible" @addUserChange="addUserChange" ref="addUserRef" />
  </el-card>
</template>
<script>
export default { name: 'backendApprovalCollectiveness' }
</script>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { http } from '@/utils/http/index';
import { Plus, Avatar, CircleClose } from "@element-plus/icons-vue";
import addNode from "./component/addNode.vue"
import addMember from "./component/addMember.vue"
import { ContentTypeEnum } from '@/enums/httpEnum';

/* 路由 */
const router = useRouter();
const route = useRoute()

onMounted(() => {
  getNodeList()
})

const flowType = computed(() => {
  const current = route.path.replace(/\/backend/g, '')
  // 社科基金
  if (current == '/approval-fund') return 0
  // 宣讲集体
  if (current == '/approval-collectiveness') return 1
  // 先进个人
  if (current == '/approval-personal') return 2
  // 优秀理论宣讲报告
  if (current == '/approval-report') return 3
  // 优秀理论宣讲微视频
  if (current == '/approval-video') return 4
  return ''
})

/* 审批流程数据 */
const nodeList = ref([])
const loading = ref(false)

/* 查询所有审批节点及审批人 */
const getNodeList = () => {
  loading.value = true
  let params = {
    dfi: {
      Logic: 0,
      Filters: [{
        Field: "flowType",
        Operator: 8,
        Value: flowType.value,
      }]
    }
  }
  
  http.$POST(`/PreachM/GetAllNodeConfig`, params).then(res => {
    loading.value = false
    if(res.isError) return ElMessage.warning("查询失败")
    nodeList.value = res.result
  }).catch(() => {
    loading.value = false
    ElMessage.warning("查询失败")
  })
}

watch(() => router.currentRoute.value.path, () => {
  getNodeList()
})

/* 添加、编辑审批节点部分 */
const addNodeVisible = ref(false)
const addNodeTitle = ref("添加审批节点")
const changeNodeType = ref("add")

/* 添加、编辑审批节点弹窗 */
const addNodeRef = ref(null)

/* 当前所选审批节点 */
const currentNode = ref({})

/* 点击新建 */
const addNodeItem = () => {
  addNodeVisible.value = true
  addNodeTitle.value = "添加审批节点"
  changeNodeType.value = "add"
}

/* 点击编辑 */
const nodeEdit = (item) => {
  currentNode.value = item
  addNodeTitle.value = "编辑审批节点"
  changeNodeType.value = "edit"
  addNodeRef.value.openDialog()
  addNodeVisible.value = true
}

/* 添加、编辑审核节点回调 */
const addNodeChange = (addResult) => {
  let params = JSON.parse(JSON.stringify(addResult))

  if(changeNodeType.value == 'edit') {
    params.configId = currentNode.value.id
    params.id = currentNode.value.id
  } else {
    params.configId = ''
    delete params.id
  }

  params.flowType = flowType.value

  http.$POST("/PreachM/AddOrUpdateNodeConfig", {...params}, { headers: { 'Content-Type': ContentTypeEnum.FORM_DATA } }).then(res => {
    if(res.isError) return ElMessage.warning("操作失败")
    ElMessage.success("操作成功")
    getNodeList()
  }).catch(() => {
    ElMessage.warning("操作失败")
  })
}

/* 点击删除审批节点 */
const nodeDelete = (item) => {
  ElMessageBox.confirm(
    '确定要删除此条审批节点吗？',
    '请确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    let params = {
      id: item.id,
      configId: item.id
    }
    http.$POST("/PreachM/DeleteNodeConfig", {...params}, { headers: { 'Content-Type': ContentTypeEnum.FORM_DATA } }).then(res => {
      if(res.isError) return ElMessage.warning("操作失败")
      ElMessage.success("操作成功")
      getNodeList()
    }).catch(() => {
      ElMessage.warning("操作失败")
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除',
    })
  })
}

/* 添加审批人弹窗 */
const addUserRef = ref(null)
const addUserVisible = ref(false)

/* 点击添加审批人 */
const addApprovalPerson = (item) => {
  addUserVisible.value = true
  currentNode.value = item
  addUserRef.value.getPersonList()
}

const addUserChange = (res) => {
  res.forEach((item) => {
    let params = {
      id: currentNode.value.id,
      nodeId: currentNode.value.id,
      nodeName: currentNode.value.nodeName,
      userId: item.Id,
      userName: item.Name
    }
    http.$POST("/PreachM/AddFlowMember", {...params}, { headers: { 'Content-Type': ContentTypeEnum.FORM_DATA } }).then(res => {
      if(res.isError) return ElMessage.warning("操作失败")
      /* ElMessage.success("操作成功") */
    }).catch(() => {
      ElMessage.warning("操作失败")
    })
  })
  setTimeout(() => {
    getNodeList()
  }, 1000)
}

/* 点击删除所选审批人信息 */
const deleteApprovalPerson = (pitem, item) => {
  ElMessageBox.confirm(
    '确定要删除该成员吗？',
    '请确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    let params = {
      id: pitem.id,
      memberId: item.id
    }
    http.$POST("/PreachM/DeleteFlowMember", {...params}, { headers: { 'Content-Type': ContentTypeEnum.FORM_DATA } }).then(res => {
      if(res.isError) return ElMessage.warning("操作失败")
      ElMessage.success("操作成功")
      getNodeList()
    }).catch(() => {
      ElMessage.warning("操作失败")
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除',
    })
  })
}

/* 拖拽 */
const oldIndex = ref(null)
const oldData = ref({})
const newIndex = ref(null)

const dragStart = (item, index) => {
  oldData.value = item
  oldIndex.value = index
}

const dragOver = (index) => {
  newIndex.value = index
}

const dragEnd = () => {
  let newData = [...nodeList.value]
  newData.splice(oldIndex.value, 1)
  newData.splice(newIndex.value, 0, oldData.value)
  nodeList.value = [...newData]
  newIndex.value = null
}
</script>

<style lang='scss' scoped>
@import "@/assets/styles/backendElement.scss";
</style>